import { TypeOrmModuleOptions } from "@nestjs/typeorm";
import { Logs } from "./logs/logs.entity";
import { Roles } from "./roles/roles.entity";
import { Profile } from "./user/profile.entity";
import { User } from "./user/user.entity";
import { DataSource, DataSourceOptions } from "typeorm";
import { readFileSync } from 'fs'
import * as yaml from 'js-yaml'
import { join } from 'path'
import * as _ from 'lodash'
import { ConfigEnum } from './enum/config.enum'

const filePath = join(__dirname, '../config', 'config.yml')
const envPath = join(__dirname, '../config', `config.${process.env.NODE_ENV}.yml`)

const fileConfig = yaml.load(readFileSync(filePath, 'utf8')) as Record<string, any>
const envConfig = yaml.load(readFileSync(envPath, 'utf8')) as Record<string, any>
function getEnvConfig(): Record<string, unknown> {
    const config = _.merge(fileConfig, envConfig)
    console.log({ config })
    return {
        type: _.get(config, ConfigEnum.DB_TYPE),
        host: _.get(config, ConfigEnum.DB_HOST),
        port: _.get(config, ConfigEnum.DB_PORT),
        username: _.get(config, ConfigEnum.DB_USERNAME),
        password: _.get(config, ConfigEnum.DB_PASSWORD),
        database: _.get(config, ConfigEnum.DB_NAME),
        entities: [User, Roles, Profile, Logs],
        synchronize: true,
        logging: ['error']
    } as TypeOrmModuleOptions
}
export const connectParams = getEnvConfig()

export default new DataSource({
    ...connectParams,
    migrations: ['src/migrations/*.ts'],
} as DataSourceOptions)